﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using UIWindows.GlobalStatics;
using UIWindows.Tools.Helper;
using XingLucifer.IBase.Enums;

namespace UIWindows
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            string device = AppDomain.CurrentDomain.BaseDirectory.Substring(0, 1);
            int count = Process.GetProcessesByName(System.Reflection.Assembly.GetEntryAssembly().FullName.Split(',')[0]).Length;
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
            if (!Directory.Exists(GlobalStatic.ConfigPath)) { _ = Directory.CreateDirectory(GlobalStatic.ConfigPath); }
            if ((count > 1) || (GetHardDiskFreeSpace(AppDomain.CurrentDomain.BaseDirectory.Substring(0, 1)) < 5))
            {
                _ = MessageBox.Show(count > 1 ? $"不可以重复打开软件！！！" : $"{device}硬盘容量过小，请手动清理垃圾或删除旧数据", "Xing丶Lucifer");
                Current.Shutdown();
            }
            //Task.Run(() =>
            //{
            //    try
            //    {
            //        Kinlo.Entitys.ProductionData.FindCount();
            //    }
            //    catch (Exception)
            //    {
            //        MessageBox.Show("数据库初始化异常!!!");
            //    }
            //});
        }

        private void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
        {
            Exception e = (Exception)args.ExceptionObject;
            e.ToString().RunLog(MessageLevelType.错误);
        }

        private static long GetHardDiskFreeSpace(string str_HardDiskName)
        {
            DriveInfo drive = DriveInfo.GetDrives().Where(x => x.Name == $"{str_HardDiskName}:\\").FirstOrDefault();
            return drive != null ? drive.TotalFreeSpace / (1024 * 1024 * 1024) : 0;
        }
    }
}
